package cn.dai.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import cn.dai.exception.TokenAuthException;
import cn.dai.pojo.ReturnCode;
import cn.dai.pojo.TokenVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author daijiyong
 * token 相关方法集合类
 */
@Component
public class TokenUtil {
    private static String privateKey;
    public static Long youngToken;
    public static Long oldToken;

    public final static String PARAM_USER_NAME_KEY = "userName";
    public final static String PARAM_PASSWORD_KEY = "password";
    public final static String PARAM_TIMESTAMP_KEY = "timestamp";
    public final static String REQUEST_HEADER_TOKEN_KEY = "token";
    public final static String REQUEST_HEADER_EXPIRES_KEY = "expires";

    /**
     * 加密token.
     */
    public static void getToken(TokenVo tokenVo) throws TokenAuthException {
        //  TODO    验证用户名和密码
        boolean pass = true;
        if (!pass) {
            throw new TokenAuthException(ReturnCode.USERNAME_OR_PASSWORD_ERROR);
        }
        tokenVo.setTimestamp(System.currentTimeMillis());
        //生成token
        String token = JWT
                .create()
                .withClaim(PARAM_USER_NAME_KEY, tokenVo.getUserName())
                .withClaim(PARAM_PASSWORD_KEY, tokenVo.getPassword())
                .withClaim(PARAM_TIMESTAMP_KEY, tokenVo.getTimestamp())
                .sign(Algorithm.HMAC256(privateKey));
        tokenVo.setToken(token);
    }

    /**
     * 解析token.
     */
    public static TokenVo parseToken(String token) {
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(token);
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(privateKey))
                .build().verify(token);
        Claim userName = decodedjwt.getClaim(PARAM_USER_NAME_KEY);
        Claim password = decodedjwt.getClaim(PARAM_PASSWORD_KEY);
        Claim timeStamp = decodedjwt.getClaim(PARAM_TIMESTAMP_KEY);
        tokenVo.setUserName(userName.asString());
        tokenVo.setPassword(password.asString());
        tokenVo.setTimestamp(timeStamp.asLong());
        return tokenVo;
    }

    @Value("${token.private-key}")
    public void setPrivateKey(String privateKey) {
        TokenUtil.privateKey = privateKey;
    }

    @Value("${token.expires.young}")
    public void setYoungToken(Long youngToken) {
        TokenUtil.youngToken = youngToken;
    }

    @Value("${token.expires.old}")
    public void setOldToken(Long oldToken) {
        TokenUtil.oldToken = oldToken;
    }
}
